import React, { useEffect, useState, useRef } from 'react'
import useStore from '../../components/useStore'
import { Button, DatePicker, Divider, Form, Input, Modal, Spin, Upload, notification, InputNumber, Select, Col, Row, Radio, Table, Space, Typography, Card } from 'antd'
import { UploadOutlined, createFromIconfontCN, LinkOutlined, PlusOutlined, MinusOutlined, SearchOutlined } from '@ant-design/icons'
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import dayjs from 'dayjs'
import request from '../../untils/request.js'

const { Option } = Select;

const IconFont = createFromIconfontCN({
  scriptUrl: require('../../../devDocument/icon.js'), // 根据实际路径调整
});

const AfterSalesUploadOrder = () => {//上传售后服务单

    const { collapsed, setnowroute } = useStore()
    const [form] = Form.useForm()
    const [afterSalesUsers, setafterSalesUsers] = useState([])//售后人员可供选择的范围
    const [main_problem_content_html, setmain_problem_content_html] = useState(BraftEditor.createEditorState(null))
    const [specific_solution_measures_html, setspecific_solution_measures_html] = useState(BraftEditor.createEditorState(null))
    
    // 添加状态管理文件
    const [problemDescriptionListFile, setProblemDescriptionListFile] = useState(null)
    const [problemSolvingSolutionFile, setProblemSolvingSolutionFile] = useState(null)
    const [uploading, setUploading] = useState(false)
    
    // 替换物料表格数据
    const [materialData, setMaterialData] = useState([]);
    const [nextId, setNextId] = useState(1);
    
    // BOM相关状态
    const [bomList, setBomList] = useState([]); // 存储BOM表数据
    const [bomLoading, setBomLoading] = useState(false); // BOM加载状态
    const [bomModalVisible, setBomModalVisible] = useState(false); // BOM选择弹窗
    const [currentMaterialId, setCurrentMaterialId] = useState(null); // 当前操作的物料ID
    const [bomSearchText, setBomSearchText] = useState(''); // BOM搜索文本
    const [currentPage, setCurrentPage] = useState(1); // 当前页码
    const [totalPages, setTotalPages] = useState(1); // 总页数
    
    // SN码搜索相关状态
    const [snOptions, setSnOptions] = useState([]);
    const [searchLoading, setSearchLoading] = useState(false);
    const searchTimeoutRef = useRef(null);
    const [snInputValue, setSnInputValue] = useState('');
    
    // 产品、站点和客户相关信息状态
    const [selectedProduct, setSelectedProduct] = useState(null); // 存储选中产品的完整信息
    const [stationInfo, setStationInfo] = useState(null); // 存储站点信息
    const [customerInfo, setCustomerInfo] = useState(null); // 存储客户信息
    const [stationLoading, setStationLoading] = useState(false); // 站点查询加载状态
    const [customerLoading, setCustomerLoading] = useState(false); // 客户查询加载状态

    // 上传方式状态管理 - 默认文件上传
    const [problemDescriptionUploadType, setProblemDescriptionUploadType] = useState('file')
    const [problemSolutionUploadType, setProblemSolutionUploadType] = useState('file')

    // 确保表单初始值与状态同步，默认选择文件上传并设置服务时间为当前时间
    useEffect(() => {
        // 获取当前时间作为默认服务时间
        const currentTime = dayjs();
        
        form.setFieldsValue({
            problem_description_upload_type: 'file',
            problem_solution_upload_type: 'file',
            service_time: currentTime // 设置服务时间默认值为当前时间
        });
    }, [form]);

    useEffect(() => {//初始化时加载售后相关人员
        // 加载售后人员
        request("/admin/user/getAfterSalesUsers").then(data => {
            setafterSalesUsers(data)
        })
    }, [])

    // 获取BOM表数据 - 新增父级料号过滤条件
    const fetchBomList = async (searchText = '', pageNum = 1) => {
        // 如果没有选择产品，不加载BOM数据
        if (!selectedProduct || !selectedProduct.product_part_number) {
            setBomList([]);
            return;
        }
        
        try {
            setBomLoading(true);
            const response = await request("/admin/bom/getBom", {
                method: "POST",
                body:{
                    number: searchText, // 按料号搜索
                    pageNum: pageNum,
                    pageSize: 10 // 每页10条数据
                }
            });
            
            if (response.code === 200 && response.data) {
                // 过滤出父级料号等于当前产品料号的物料
                const filteredList = response.data.list.filter(
                    item => item.parentNumber === selectedProduct.product_part_number
                );
                
                setBomList(filteredList);
                setTotalPages(Math.ceil(filteredList.length / 10) || 1);
                setCurrentPage(pageNum);
            } else {
                setBomList([]);
                notification.warning({ message: "未查询到BOM数据" });
            }
        } catch (error) {
            notification.error({ message: "获取BOM数据失败，请稍后重试" });
            setBomList([]);
        } finally {
            setBomLoading(false);
        }
    };

    /**前往excel表格导入*/
    const toExcel = async () => {
        setnowroute({ ...{ route: "/ship/afterSales/afterSalesExcelForm", title: "excel导入售后服务单" } })
    }

    // 根据客户ID查询客户信息
    const fetchCustomerInfo = async (customerId) => {
        if (!customerId || isNaN(Number(customerId))) {
            setCustomerInfo(null);
            return;
        }
        
        try {
            setCustomerLoading(true);
            const response = await request("/admin/customer/getCustomers", {
                method: "POST",
                body:{
                    id: Number(customerId) // 通过客户ID查询客户信息
                }
            });
            
            if (response.code === 200 && response.data) {
                setCustomerInfo(response.data); // 存储查询到的客户信息
            } else {
                setCustomerInfo(null);
                notification.warning({ message: "未查询到相关客户信息" });
            }
        } catch (error) {
            notification.error({ message: "查询客户信息失败，请稍后重试" });
            setCustomerInfo(null);
        } finally {
            setCustomerLoading(false);
        }
    };

    // 根据站点ID查询站点信息
    const fetchStationInfo = async (stationId) => {
        if (!stationId || isNaN(Number(stationId))) {
            setStationInfo(null);
            setCustomerInfo(null); // 清空站点信息时同时清空客户信息
            return;
        }
        
        try {
            setStationLoading(true);
            const response = await request("/admin/station/getStations", {
                method: "POST",
                body: {
                    id: Number(stationId) // 使用带前缀的站点接口通过ID查询
                }
            });
            
            if (response.code === 200 && response.data && response.data.length > 0) {
                setStationInfo(response.data[0]); // 存储查询到的站点信息
                
                // 如果站点信息包含客户ID，查询客户信息
                if (response.data[0].customer_id) {
                    fetchCustomerInfo(response.data[0].customer_id);
                } else {
                    setCustomerInfo(null);
                }
            } else {
                setStationInfo(null);
                setCustomerInfo(null);
                notification.warning({ message: "未查询到相关站点信息" });
            }
        } catch (error) {
            notification.error({ message: "查询站点信息失败，请稍后重试" });
            setStationInfo(null);
            setCustomerInfo(null);
        } finally {
            setStationLoading(false);
        }
    };

    // SN码实时搜索处理
    const handleSnSearch = async (value) => {
        // 保存输入值
        setSnInputValue(value);
        
        // 清除之前的超时任务，避免频繁请求
        if (searchTimeoutRef.current) {
            clearTimeout(searchTimeoutRef.current);
        }
        
        // 如果输入为空，清空选项和产品信息
        if (!value || value.trim() === '') {
            setSnOptions([]);
            setSelectedProduct(null);
            setStationInfo(null);
            setCustomerInfo(null);
            return;
        }
        
        // 延迟搜索，减少请求次数
        searchTimeoutRef.current = setTimeout(async () => {
            try {
                setSearchLoading(true);
                // 调用后端接口查询匹配的SN码
                const response = await request("/admin/product/getProducts", {
                    method: "POST",
                    body: {
                        sn: value.trim(),
                        pageSize: 10, // 只获取前10条匹配结果
                        offset: 0
                    }
                });
                
                if (response.code === 200 && response.data.length > 0) {
                    setSnOptions(response.data);
                } else {
                    setSnOptions([]);
                    setSelectedProduct(null);
                    setStationInfo(null);
                    setCustomerInfo(null);
                }
            } catch (error) {
                notification.error({ message: "SN码搜索失败，请稍后重试" });
            } finally {
                setSearchLoading(false);
            }
        }, 300); // 300ms延迟，等待用户停止输入
    };

    // 处理SN码选择变化 - 新增清除物料逻辑
    const handleSnChange = (value) => {
        setSnInputValue(value);
        
        // 查找选中的产品完整信息
        const selected = snOptions.find(item => item.sn === value);
        setSelectedProduct(selected);
        
        // 重新选择SN时清除已添加的物料
        setMaterialData([]);
        setNextId(1);
        
        // 如果有站点ID，查询站点信息（会自动触发客户信息查询）
        if (selected && selected.station_id) {
            fetchStationInfo(selected.station_id);
        } else {
            setStationInfo(null);
            setCustomerInfo(null);
        }
    };

    // 物料表格操作
    const addMaterial = () => {
        // 只有选择了产品SN才能添加物料
        if (!selectedProduct || !selectedProduct.product_part_number) {
            notification.warning({ message: "请先选择产品SN码" });
            return;
        }
        
        const newMaterial = {
            id: nextId,
            code: '', // 产品料号
            name: '', // 元件名称
            specification: '', // 规格型号
            money: 0,
            number: 1
        };
        setMaterialData([...materialData, newMaterial]);
        setNextId(nextId + 1);
    };

    const removeMaterial = (id) => {
        setMaterialData(materialData.filter(item => item.id !== id));
    };

    const handleMaterialChange = (id, field, value) => {
        setMaterialData(materialData.map(item => 
            item.id === id ? { ...item, [field]: value } : item
        ));
    };

    // 打开BOM选择弹窗 - 添加权限检查
    const openBomSelection = (id) => {
        // 只有选择了产品SN才能打开BOM选择
        if (!selectedProduct || !selectedProduct.product_part_number) {
            notification.warning({ message: "请先选择产品SN码" });
            return;
        }
        
        setCurrentMaterialId(id);
        setBomModalVisible(true);
        // 重置搜索文本和页码
        setBomSearchText('');
        // 重新加载BOM数据
        fetchBomList('', 1);
    };

    // 选择BOM物料
    const selectBomItem = (bomItem) => {
        // 更新物料信息
        setMaterialData(materialData.map(item => 
            item.id === currentMaterialId 
                ? { 
                    ...item, 
                    code: bomItem.number, // 产品料号
                    name: bomItem.productName, // 元件名称
                    specification: bomItem.specificationAndModel // 规格型号
                  } 
                : item
        ));
        // 关闭弹窗
        setBomModalVisible(false);
    };

    // 搜索BOM物料
    const handleBomSearch = (value) => {
        setBomSearchText(value);
        fetchBomList(value, 1); // 搜索时重置到第一页
    };

    // 处理分页
    const handleTableChange = (pagination) => {
        fetchBomList(bomSearchText, pagination.current);
    };

    const handleBeforeUpload = (fileType) => (file) => {
        // 文件类型和大小验证
        const isPDF = file.type === 'application/pdf';
        const isWord = file.type === 'application/msword' || file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
        const isExcel = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        const isLt20M = file.size / 1024 / 1024 < 20; // 限制20MB以内

        if (!isPDF && !isWord && !isExcel) {
            notification.error({ message: '仅支持PDF、Word和Excel文件格式' });
            return false;
        }
        
        if (!isLt20M) {
            notification.error({ message: '文件大小不能超过20MB' });
            return false;
        }

        // 保存文件
        switch (fileType) {
            case "problem_description_list":
                setProblemDescriptionListFile(file)
                break
            case "problem_solving_solution":
                setProblemSolvingSolutionFile(file)
                break
        }
        return false
    }

    const submit = async () => {
        try {
            const values = await form.validateFields()
            const formData = new FormData()
            setUploading(true)
            
            // 添加文本字段（服务单号由系统自动生成，不再由前端提供）
            formData.append('main_problem_content_html', BraftEditor.createEditorState(main_problem_content_html).toHTML())//上传主要问题内容富文本
            formData.append('specific_solution_measures_html', BraftEditor.createEditorState(specific_solution_measures_html).toHTML())//上传具体解决方案措施富文本
            formData.append('sn', values.sn)
            
            // 产品相关信息（销售单号和站点ID）
            if (selectedProduct) {
                if (selectedProduct.sales_order_id) {
                    formData.append('sales_order_id', selectedProduct.sales_order_id);
                }
                if (selectedProduct.station_id) {
                    formData.append('station_id', selectedProduct.station_id);
                }
            }
            
            // 日期字段（特殊处理）
            if (values.service_time) {
                formData.append('service_time', dayjs(values.service_time).format('YYYY-MM-DD HH:mm:ss'));
            }

            // 基础字段（只在值存在时添加）
            if (values.after_sales_person_id !== null && values.after_sales_person_id !== undefined) {
                formData.append('after_sales_person_id', values.after_sales_person_id);
            }

            if (values.money !== null && values.money !== undefined) {
                formData.append('money', values.money);
            }

            if (values.time !== null && values.time !== undefined) {
                formData.append('time', values.time);
            }

            // 添加替换物料数据 - 只发送产品料号(code)
            if (materialData.length > 0) {
                formData.append('materials', JSON.stringify(
                    materialData.map(item => ({
                        code: item.code,
                        money: item.money,
                        number: item.number
                    }))
                ));
            }

            // 问题描述清单 - 根据上传类型添加
            if (problemDescriptionUploadType === 'file' && problemDescriptionListFile) {
                formData.append('problem_description_list', problemDescriptionListFile);
            } else if (problemDescriptionUploadType === 'reference' && values.problem_description_reference) {
                formData.append('problem_description_reference', values.problem_description_reference);
            }

            // 问题解决方案 - 根据上传类型添加
            if (problemSolutionUploadType === 'file' && problemSolvingSolutionFile) {
                formData.append('problem_solving_solution', problemSolvingSolutionFile);
            } else if (problemSolutionUploadType === 'reference' && values.problem_solution_reference) {
                formData.append('problem_solution_reference', values.problem_solution_reference);
            }

            // 发送表单数据
            fetch("/admin/afterSales/uploadOrder", {
                method: "POST",
                body: formData,
                headers:{
                    Authorization: `Bearer ${JSON.parse(localStorage.getItem('user')).token}`
                }
            }).then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        notification.success({
                            message: "上传成功"
                        })
                        // 重置表单状态
                        setProblemDescriptionListFile(null);
                        setProblemSolvingSolutionFile(null);
                        setMaterialData([]);
                        setNextId(1);
                        form.resetFields();
                        setSnInputValue('');
                        setSnOptions([]);
                        setSelectedProduct(null);
                        setStationInfo(null);
                        setCustomerInfo(null);
                    } else {
                        notification.error({
                            message: data.msg || "上传失败"
                        })
                    }
                    setTimeout(() => {
                        setUploading(false)
                    }, 300)
                }).catch(() => {
                    notification.error({ message: "网络错误，上传失败" });
                    setUploading(false);
                })
        } catch (errorInfo) {
            notification.error({
                message: "请检查填写信息是否有误"
            })
            setUploading(false);
        }
    }

    // BOM表格列定义 - 调整字段显示名称
    const bomColumns = [
        {
            title: '产品料号',
            dataIndex: 'number',
            key: 'number',
        },
        {
            title: '父级产品料号',
            dataIndex: 'parentNumber',
            key: 'parentNumber',
        },
        {
            title: '元件名称',
            dataIndex: 'productName',
            key: 'productName',
        },
        {
            title: '规格型号',
            dataIndex: 'specificationAndModel',
            key: 'specificationAndModel',
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Button type="link" onClick={() => selectBomItem(record)}>选择</Button>
            ),
        },
    ];

    // 物料表格列定义 - 移除手动输入，只能从BOM选择
    const materialColumns = [
        {
            title: '产品料号',
            dataIndex: 'code',
            key: 'code',
            width: '20%', // 增加宽度比例
            render: (text, record) => (
                <Space size="small" style={{ width: '100%' }}>
                    <Input 
                        value={text}
                        placeholder="请选择BOM物料"
                        style={{ flex: 1, minWidth: 0 }} // 使用flex确保输入框适应空间
                        readOnly
                    />
                    <Button 
                        type="primary" 
                        size="small" 
                        onClick={() => openBomSelection(record.id)}
                        style={{ whiteSpace: 'nowrap' }} // 防止按钮文字换行
                    >
                        选择BOM
                    </Button>
                </Space>
            )
        },
        {
            title: '元件名称',
            dataIndex: 'name',
            key: 'name',
            width: '20%',
            render: (text) => (
                <Input 
                    value={text}
                    placeholder="选择BOM后自动填充"
                    readOnly
                    style={{ width: '100%' }}
                />
            )
        },
        {
            title: '规格型号',
            dataIndex: 'specification',
            key: 'specification',
            width: '20%',
            render: (text) => (
                <Input 
                    value={text}
                    placeholder="选择BOM后自动填充"
                    readOnly
                    style={{ width: '100%' }}
                />
            )
        },
        {
            title: '价格',
            dataIndex: 'money',
            key: 'money',
            width: '15%',
            render: (text, record) => (
                <InputNumber 
                    value={text}
                    onChange={(value) => handleMaterialChange(record.id, 'money', value)}
                    precision={2}
                    style={{ width: '100%' }}
                    placeholder="0.00"
                />
            )
        },
        {
            title: '数量',
            dataIndex: 'number',
            key: 'number',
            width: '15%',
            render: (text, record) => (
                <InputNumber 
                    value={text}
                    onChange={(value) => handleMaterialChange(record.id, 'number', value)}
                    min={1}
                    style={{ width: '100%' }}
                    placeholder="1"
                />
            )
        },
        {
            title: '操作',
            key: 'action',
            width: '10%', // 固定操作列宽度
            render: (_, record) => (
                <Space size="middle">
                    <Button 
                        type="text" 
                        danger 
                        icon={<MinusOutlined />} 
                        onClick={() => removeMaterial(record.id)}
                        size="small" // 使用小尺寸按钮节省空间
                        style={{ padding: '4px 8px' }}
                    >
                        删除
                    </Button>
                </Space>
            )
        }
    ];
    
    return (
        <div style={{ 
            height: "94%", backgroundColor: `#F1F1F1`, right: "1%", top: "4vh", overflow: "hidden",
            backgroundSize: "100% 100%", width: collapsed ? "94%" : "84%", position: "absolute",  
            color: "white", fontSize: "0.8rem"
        }}>
            <div style={styles.kshcontainer}>
                <div style={{
                    fontSize: "0.7rem", position: "relative", width: "96%", marginLeft: "2%", 
                    display: "flex", textIndent: "1rem", justifyContent: "flex-start", 
                    alignContent: "flex-start", flexWrap: "wrap",
                    maxHeight: "80vh", 
                    overflowY: "auto", 
                    overflowX: "hidden" ,
                    paddingBottom: "2vh"
                }}>
                    <Button type="primary" onClick={toExcel} style={{ marginTop: "2vh" }}>
                        <IconFont type="icon-Excel" />通过excel表格导入
                    </Button>
                    <Divider />
                    <Form
                        style={{ marginTop: "2vh", width: "95%" }}
                        form={form}
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 18 }}
                    >
                        {/* 基础信息模块 */}
                        <Row gutter={24}>
                            <Col span={12}>
                                <Form.Item
                                    label="对应产品SN"
                                    name="sn"
                                    rules={[{ required: true, message: '对应产品SN不能为空' }]}
                                >
                                    <Select
                                        showSearch
                                        value={snInputValue}
                                        placeholder="请输入产品SN码，支持边输入边搜索"
                                        style={{ width: '100%' }}
                                        loading={searchLoading}
                                        onSearch={handleSnSearch}
                                        onChange={handleSnChange}
                                        filterOption={false} // 关闭内置过滤，使用我们自己的搜索逻辑
                                        allowClear
                                    >
                                        {snOptions.map(item => (
                                            <Option key={item.sn} value={item.sn}>
                                                <div style={{ display: 'flex', flexDirection: 'column' }}>
                                                    <span>{item.sn}</span>
                                                </div>
                                            </Option>
                                        ))}
                                    </Select>
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item
                                    label="服务时间"
                                    name="service_time"
                                >
                                    <DatePicker showTime placeholder='请选择服务时间' />
                                </Form.Item>
                            </Col>
                        </Row>
                        
                        <text>
                            质保日期:{selectedProduct?.quality_guarantee_date || '无'}
                        </text>

                        {/* 产品关联信息展示区域 */}
                        {(selectedProduct || stationInfo || customerInfo) && (
                            <Row gutter={24} style={{ marginBottom: 16 }}>
                                <Col span={24}>
                                    <Card title="产品关联信息" bordered style={{ marginLeft: '10rem' }}>
                                        <Row gutter={16}>
                                            {/* 销售单号展示 */}
                                            <Col span={6}>
                                                <div style={{ fontWeight: 'bold' }}>销售单号:</div>
                                                <div style={{ marginTop: 4 }}>
                                                    {selectedProduct?.sales_order_id || '无'}
                                                </div>
                                            </Col>
                                            
                                            {/* 产品料号展示 */}
                                            <Col span={6}>
                                                <div style={{ fontWeight: 'bold' }}>产品料号:</div>
                                                <div style={{ marginTop: 4 }}>
                                                    {selectedProduct?.product_part_number || '无'}
                                                </div>
                                            </Col>
                                            
                                            {/* 站点信息展示 */}
                                            <Col span={6}>
                                                <div style={{ fontWeight: 'bold' }}>站点信息:</div>
                                                <div style={{ marginTop: 4 }}>
                                                    {stationLoading ? (
                                                        <Spin size="small" />
                                                    ) : stationInfo ? (
                                                        <>
                                                            <div>站点名称: {stationInfo.name}</div>
                                                            <div>站点ID: {stationInfo.id}</div>
                                                        </>
                                                    ) : selectedProduct?.station_id ? (
                                                        '未查询到站点信息'
                                                    ) : (
                                                        '无'
                                                    )}
                                                </div>
                                            </Col>
                                            
                                            {/* 客户信息展示 */}
                                            <Col span={6}>
                                                <div style={{ fontWeight: 'bold' }}>客户信息:</div>
                                                <div style={{ marginTop: 4 }}>
                                                    {customerLoading ? (
                                                        <Spin size="small" />
                                                    ) : customerInfo ? (
                                                        <>
                                                            <div>客户名称: {customerInfo.name}</div>
                                                            <div>客户ID: {customerInfo.id}</div>
                                                        </>
                                                    ) : stationInfo?.customer_id ? (
                                                        '未查询到客户信息'
                                                    ) : (
                                                        '无'
                                                    )}
                                                </div>
                                            </Col>
                                        </Row>
                                    </Card>
                                </Col>
                            </Row>
                        )}

                        <Row gutter={24}>
                            <Col span={12}>
                                <Form.Item
                                    label="售后人员"
                                    name="after_sales_person_id"
                                >
                                    <Select options={afterSalesUsers} placeholder="请选售后人员" />
                                </Form.Item>
                            </Col>
                        </Row>

                        {/* 数值输入模块 */}
                        <Row gutter={24}>
                            <Col span={12}>
                                <Form.Item
                                    label="服务费用"
                                    name="money"
                                    rules={[{
                                        validator: (_, value) => {
                                            if (!value && value !== 0) return Promise.resolve();
                                            const strValue = value.toString();
                                            if (strValue.replace(/[.]/, '').length > 15) {
                                                return Promise.reject(new Error('服务费用总长度不能超过15位'));
                                            }
                                            return Promise.resolve();
                                        }
                                    }]}
                                >
                                    <InputNumber
                                        precision={2}
                                        step={0.01}
                                        formatter={value => value?.toString()}
                                        parser={value => value.replace(/[^\d.]/g, '')}
                                        style={{ width: '100%' }}
                                        placeholder='服务费用最长为15位数（含小数点与小数）'
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item
                                    label="工时"
                                    name="time"
                                    rules={[{
                                        validator: (_, value) => {
                                            if (!value && value !== 0) return Promise.resolve();
                                            const strValue = value.toString();
                                            if (strValue.replace(/[.]/, '').length > 5) {
                                                return Promise.reject(new Error('总长度不能超过5位'));
                                            }
                                            return Promise.resolve();
                                        }
                                    }]}
                                >
                                    <InputNumber
                                        precision={1}
                                        step={0.1}
                                        formatter={value => value?.toString()}
                                        parser={value => value.replace(/[^\d.]/g, '')}
                                        style={{ width: '100%' }}
                                        placeholder='数量最长为5位数（含小数点与小数）'
                                    />
                                </Form.Item>
                            </Col>
                        </Row>

                        {/* 替换物料表格 */}
                        <Row>
                            <Col span={24}>
                                <Typography.Title level={5} style={{ marginLeft: '10rem', marginBottom: 16 }}>
                                    需要替换物料
                                </Typography.Title>
                                <div style={{ marginLeft: '10rem' }}>
                                    {/* 已移除未选择SN时的提示信息 */}
                                    
                                    <Table
                                        columns={materialColumns}
                                        dataSource={materialData}
                                        pagination={false}
                                        bordered
                                        locale={{ emptyText: '暂无物料信息，点击添加按钮添加' }}
                                    />
                                    <Button 
                                        type="dashed" 
                                        icon={<PlusOutlined />} 
                                        onClick={addMaterial}
                                        style={{ marginTop: 16, width: '100%' }}
                                        disabled={!selectedProduct} // 未选择产品时禁用添加按钮
                                    >
                                        添加物料
                                    </Button>
                                </div>
                            </Col>
                        </Row>

                        {/* 富文本模块 - 移至附件上传上方 */}
                        <Row>
                            <Col span={12}>
                                <Form.Item
                                    name="main_problem_content_html"
                                    label="主要问题内容"
                                >
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={24}>
                                <Form.Item>
                                    <BraftEditor
                                        style={{ height: "20vh !important", marginLeft: "10rem", border: "1px solid #d9d9d9", borderRadius: 4 }}
                                        value={main_problem_content_html}
                                        onChange={setmain_problem_content_html}
                                        placeholder="请编辑主要问题内容"
                                        media={{ uploadFn: () => {} }}
                                        excludeControls={["media"]}
                                    />
                                </Form.Item>
                            </Col>
                        </Row>

                        <Row>
                            <Col span={12}>
                                <Form.Item
                                    name="specific_solution_measures_html"
                                    label="具体解决方案措施"
                                >
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={24}>
                                <Form.Item>
                                    <BraftEditor
                                        style={{ height: "20vh !important", marginLeft: "10rem", border: "1px solid #d9d9d9", borderRadius: 4 }}
                                        value={specific_solution_measures_html}
                                        onChange={setspecific_solution_measures_html}
                                        placeholder="请编辑具体解决方案措施"
                                        media={{ uploadFn: () => {} }}
                                        excludeControls={["media"]}
                                    />
                                </Form.Item>
                            </Col>
                        </Row>

                        {/* 附件上传模块 */}
                        <Row>
                            <Col span={24}>
                                <h3 style={{ margin: '16px 0', color: '#1890ff', borderLeft: '3px solid #1890ff', paddingLeft: 12 }}>附件上传</h3>
                            </Col>
                        </Row>

                        <Row gutter={24}>
                            {/* 问题描述清单上传区域 */}
                            <Col span={12}>
                                <Form.Item
                                    label="问题描述清单上传方式"
                                    name="problem_description_upload_type"
                                >
                                    <Radio.Group 
                                        value={problemDescriptionUploadType}
                                        onChange={e => setProblemDescriptionUploadType(e.target.value)}
                                        buttonStyle="solid"
                                        style={{ width: '100%' }}
                                    >
                                        <Radio.Button value="file" icon={<UploadOutlined />} style={{ flex: 1 }}>直接上传文件</Radio.Button>
                                        <Radio.Button value="reference" icon={<LinkOutlined />} style={{ flex: 1 }}>引用单号</Radio.Button>
                                    </Radio.Group>
                                </Form.Item>

                                {problemDescriptionUploadType === 'file' && (
                                    <Form.Item
                                        label="问题描述清单文件"
                                        name="problem_description_list"
                                    >
                                        <Upload
                                            maxCount={1}
                                            beforeUpload={handleBeforeUpload('problem_description_list')}
                                            onRemove={() => {
                                                setProblemDescriptionListFile(null);
                                                return true;
                                            }}
                                            fileList={problemDescriptionListFile ? [{
                                                uid: problemDescriptionListFile.uid || Date.now().toString(),
                                                name: problemDescriptionListFile.name,
                                                status: 'done'
                                            }] : []}
                                        >
                                            <Button icon={<UploadOutlined />}>选择文件</Button>
                                        </Upload>
                                    </Form.Item>
                                )}

                                {problemDescriptionUploadType === 'reference' && (
                                    <Form.Item
                                        label="问题描述清单引用单号"
                                        name="problem_description_reference"
                                    >
                                        <Input maxLength={50} showCount placeholder='请输入要引用的单号' />
                                    </Form.Item>
                                )}
                            </Col>

                            {/* 问题解决方案上传区域 */}
                            <Col span={12}>
                                <Form.Item
                                    label="问题解决方案上传方式"
                                    name="problem_solution_upload_type"
                                >
                                    <Radio.Group 
                                        value={problemSolutionUploadType}
                                        onChange={e => setProblemSolutionUploadType(e.target.value)}
                                        buttonStyle="solid"
                                        style={{ width: '100%' }}
                                    >
                                        <Radio.Button value="file" icon={<UploadOutlined />} style={{ flex: 1 }}>直接上传文件</Radio.Button>
                                        <Radio.Button value="reference" icon={<LinkOutlined />} style={{ flex: 1 }}>引用单号</Radio.Button>
                                    </Radio.Group>
                                </Form.Item>

                                {problemSolutionUploadType === 'file' && (
                                    <Form.Item
                                        label="问题解决方案文件"
                                        name="problem_solving_solution"
                                    >
                                        <Upload
                                            maxCount={1}
                                            beforeUpload={handleBeforeUpload('problem_solving_solution')}
                                            onRemove={() => {
                                                setProblemSolvingSolutionFile(null);
                                                return true;
                                            }}
                                            fileList={problemSolvingSolutionFile ? [{
                                                uid: problemSolvingSolutionFile.uid || Date.now().toString(),
                                                name: problemSolvingSolutionFile.name,
                                                status: 'done'
                                            }] : []}
                                        >
                                            <Button icon={<UploadOutlined />}>选择文件</Button>
                                        </Upload>
                                    </Form.Item>
                                )}

                                {problemSolutionUploadType === 'reference' && (
                                    <Form.Item
                                        label="问题解决方案引用单号"
                                        name="problem_solution_reference"
                                    >
                                        <Input maxLength={50} showCount placeholder='请输入要引用的单号' />
                                    </Form.Item>
                                )}
                            </Col>
                        </Row>

                        {/* 提交按钮 */}
                        <Row>
                            <Col span={24}>
                                <Button type="primary" onClick={submit}>提交订单</Button>
                            </Col>
                        </Row>
                    </Form>
                    {/* 上传加载模态框 */}
                    <Modal
                        open={uploading}
                        centered
                        closable={false}
                        footer={null}
                        maskClosable={false}
                        width={400}
                        bodyStyle={{ textAlign: 'center', padding: '30px 20px' }}
                    >
                        <Spin />
                        <div style={{ marginTop: 20, fontSize: 16, fontWeight: 'bold', color: '#333' }}>
                            上传中
                        </div>
                        <div style={{ marginTop: 10, color: '#666' }}>
                            请勿关闭页面或进行其他操作
                        </div>
                    </Modal>

                    {/* BOM选择弹窗 */}
                    <Modal
                        title="选择BOM物料"
                        open={bomModalVisible}
                        onCancel={() => setBomModalVisible(false)}
                        footer={null}
                        width={800}
                    >
                        <div style={{ marginBottom: 16 }}>
                            <Input
                                placeholder="请输入产品料号搜索"
                                value={bomSearchText}
                                onChange={(e) => handleBomSearch(e.target.value)}
                                prefix={<SearchOutlined />}
                            />
                        </div>
                        {/* 已移除父级料号提示信息 */}
                        <Table
                            columns={bomColumns}
                            dataSource={bomList}
                            rowKey="id"
                            loading={bomLoading}
                            pagination={{ 
                                current: currentPage,
                                total: totalPages * 10, // 估算总条数
                                pageSize: 10,
                                showSizeChanger: false
                            }}
                            onChange={handleTableChange}
                            scroll={{ y: 400 }}
                            locale={{ emptyText: '未找到符合条件的物料' }}
                        />
                    </Modal>
                </div>
            </div>
        </div>
    )
}

export default AfterSalesUploadOrder

var styles = {
    kshcontainer: {
        width: "98%", 
        height: "95%", 
        position: "absolute", top: "3%", 
        left: "1%", backgroundColor: "white", 
        color: "black",
        borderRadius: "10px",
    },
}
    